//
//  SelectMapPointView2.swift
//  JiaoZiTaxi
//
//  Created by shanzachattha8@gmail.comArmy1122@ on 2025/5/24.
//

import SwiftUI
import MapKit

struct CommonAddressView: View {
    @Environment(\.dismiss) var dismiss
    @StateObject private var addressManager = MyAddressNetManager()
    @State private var isEditing = false
    var action : ()->Void
    
    @State private var selectedAddress: AddressModel?
    
    func getEditIndex(addr:AddressModel)->Int{
        if let index = addressManager.addressCommonList.firstIndex(where: { $0 == addr }) {
            return index
        }
        return -1
    }
    
    var body: some View {
        ZStack{
            
            NavigationLink(
                destination: selectedAddress != nil ?
                AddCommonAddressView(address: selectedAddress!,editIndex: getEditIndex(addr: selectedAddress!)) :
                AddCommonAddressView(),
                isActive: $isEditing
            ) {
                EmptyView()
            }
            .opacity(0)
            .disabled(selectedAddress == nil)
            
            NavigationView {
                VStack(alignment: .leading){
                    
                        Image(systemName: "chevron.backward").foregroundColor(Color(hex: 0x333333))
                            .aspectRatio(contentMode: .fit).onTapGesture {
                                dismiss()
                            }.padding(.vertical,15)
                    List{
                        Section(
                            header:EmptyView(),
                            footer:NavigationLink (destination:  AddCommonAddressView()){
                                HStack(){
                                    Image("首页_设置常用地址")
                                        .resizable()
                                        .frame(width: 16, height: 16)
                                    
                                    Text("设置常用地址").font(.system(size: 16,weight: .bold))
                                        .foregroundColor(Color.themeColor())
                                        .frame(maxWidth: .infinity, alignment: .leading)
                                }.padding(.horizontal,15)
                                    .padding(.vertical,15)
                                    .cornerRadius(5)
                                    .background(.white)
                            }   .frame(maxWidth: .infinity, alignment: .leading)
                                .listRowSeparator(.hidden).background(.white)
                                .overlay(
                                    HStack {
                                        Spacer()
                                        // 用空视图或自定义内容覆盖箭头位置
                                        Color.white.frame(width: 20)
                                    }
                                )
                        )
                        {
                            
                            if addressManager.addressCommonList.count > 0 {
                                HStack{
                                    Text("常用地址").font(.system(size: 18,weight: .bold)).foregroundColor(.black).padding(.leading,15)
                                    Spacer()
                                    Text("清空").font(.system(size: 12)).foregroundColor(.gray).frame(width:60, height: 44)
                                        .onTapGesture(){
                                        addressManager.clearCommonAddressList()
                                    }
                                }.frame(maxWidth: .infinity, alignment: .leading).listRowSeparator(.hidden).background(.white)
                            }
                            
                                ForEach(addressManager.addressCommonList, id: \.self) { address in
                                    Button {
                                        
                                            let lat = address.latitude
                                            let lon = address.longitude
                                            let pos = CLLocationCoordinate2D(latitude: lat!, longitude: lon!)
                                            
                                                ViewModel.shared.endLocation = pos
                                            CarOrder.shared.endPos = pos
                                                MapConfig.shared.startOrEndChanged = true
                                            CarOrder.shared.endLabel = "\(address.name ?? "")"
                                        
                                            dismiss()
                                            self.action()
                                        
                                    } label: {
                                        createPublicCell(address: address)
                                    }
                                }
                        }
                        .listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0)) // 移除行内边距
                    }
                    .listStyle(PlainListStyle())           // 移除默认样式
                    .padding(.horizontal, 0)     // 移除水平边距
                      // 确保背景透明
                }.padding(.horizontal,15)
                    .background(Color.backgroundColor())
                .onAppear {
                    addressManager.loadCommonAddressList()
                }.background(.clear)// 隐藏默认返回按钮
    //                .navigationBarItems(leading: backButton) // 添加自定义返回按钮
    //
            }
            .navigationBarHidden(true)
            
        }
       
    }
    func createPublicCell(address : AddressModel) -> some View{
        HStack{
            Image("地图选点_设置")
            Text("\(address.name!)").font(.system(size: 14))
            Spacer()
            Button {
                print("地图_编辑 address:\(address.name ?? "")")
                selectedAddress = address
                isEditing = true
            } label: {
                Image("地图_编辑")
            }
            Spacer.width(20)
            Button {
                print("地图_删除 address:\(address.name  ?? "")")
                addressManager.deleteCommonAddress(index: getEditIndex(addr: address))
            } label: {
                Image("地图_删除")
            }
        }.frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal,15).padding(.vertical,20)
    }
    
    
    var backButton: some View {
        Button(action: {
            dismiss()
            self.action()
        }) {
            HStack {
                Image(systemName: "chevron.backward")
                    .foregroundColor(.black)
            }
        }
    }
}



